package com.kurumi.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.kurumi.bo.Page;
import com.kurumi.bo.PageData;
import com.kurumi.bo.PageParam;
import com.kurumi.pojo.admin.AdminUser;
import com.kurumi.service.admin.AdminUserServcie;
import com.kurumi.util.JsonUtil;
import com.kurumi.util.MD5;

@Controller
@RequestMapping("/admin")
public class AdminUserController {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private AdminUserServcie adminUserServcie;

	@RequestMapping("/login")
	public String login() {

		return "admin/login";
	}

	@RequestMapping("/index")
	public String index() {

		System.out.println("index");

		return "admin/index";
	}

	@RequestMapping("/main")
	public String main() {

		return "admin/main";
	}

	/**
	 * 用户登陆
	 * 
	 * @param username 用户名
	 * @param password 密码
	 * @param request
	 * @param model
	 * @return
	 */
	@PostMapping("/userLogin")
	public String login(String username, String password, HttpServletRequest request, Model model) {

		try {

			if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
				model.addAttribute("errorMsg", "用户名和密码不可为空!");
				return "admin/login";
			}

			AdminUser adminUser = adminUserServcie.getUserByUsernameAndPassword(username, password);
			if (adminUser == null) {
				model.addAttribute("errorMsg", "用户名或密码错误!");
				return "admin/login";
			}

			Subject subject = SecurityUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(username, adminUser.getPassword());
			Session session = subject.getSession();
			subject.login(token);
			session.setAttribute("user", adminUser);

			return "redirect:/admin/index";
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("登陆系统异常，异常信息{}", e.getStackTrace());
			model.addAttribute("errorMsg", "用户名和密码错误!");
			return "/admin/login";
		}

	}

	/**
	 * 推出登陆
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		// 获取shiro的subiect获取session
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		// 获取cookie
		session.setAttribute("user", null);

		// shiro退出
		if (subject.isAuthenticated()) {
			subject.logout();
		}
		return "admin/login";
	}

	/**
	 * 跳转到用户信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toAdminUserListPage")
	public ModelAndView toAdminUserListPage() throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();

		return new ModelAndView("/admin/adminUserListPage", model);
	}

	@ResponseBody
	@RequestMapping(value = "/getAdminUserList")
	public void getAdminUserList(HttpServletRequest request, HttpServletResponse response, PageParam pageParam)
			throws Exception {
		Page pager = new Page();
		pager.setPage(pageParam.getPage());
		pager.setRecPerPage(pageParam.getLimit());

		PageData<AdminUser> pd = new PageData<AdminUser>();
		PageInfo<AdminUser> pageInfo = adminUserServcie.geAdminUserPageInfo(request, pageParam);

		List<AdminUser> list = pageInfo.getList();

		if (list != null && list.size() > 0) {
			pd.setCount((int) pageInfo.getTotal());
			pd.setData(list);
		} else {
			pd.setCount(0);
			pd.setData(new ArrayList<AdminUser>());
		}

		String json = JsonUtil.objectToJson(pd);

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(json);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 跳转到用户信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/adminUserAddPage")
	public ModelAndView adminUserAddPage(Integer adminUserId) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();

		AdminUser adminUser = adminUserServcie.getAdminUserById(adminUserId);
		model.put("adminUser", adminUser);
		model.put("view", adminUser == null ? null : 1);

		return new ModelAndView("/admin/adminUserAddPage", model);
	}

	/**
	 * 跳转到用户信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateUserPassword")
	public ModelAndView updateUserPassword(Integer adminUserId) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		return new ModelAndView("/admin/updateUserPassword", model);
	}

	@ResponseBody
	@RequestMapping(value = "/updateAdminUserPassword")
	public void updateAdminUserPassword(HttpServletRequest request, HttpServletResponse response, Integer adminUserId,
			String password, String newPassword) throws Exception {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out;

		JSONObject jsonObject = new JSONObject();

		try {
			
			AdminUser oldAdminUser = adminUserServcie.getAdminUserById(adminUserId);
			if(oldAdminUser!=null) {
				String oldPassword = oldAdminUser.getPassword();
				if(!oldPassword.equals(MD5.md5(password))) {
					jsonObject.put("code", "2");
					jsonObject.put("msg", "输入密码和原密码不一致!");
				}else {
					AdminUser adminUser = adminUserServcie.updateAdminUserPassword(adminUserId, newPassword);
					if(adminUser!=null) {
						request.getSession().setAttribute("user", adminUser);
					}

					jsonObject.put("code", "1");
					jsonObject.put("msg", "操作成功");
				}
			}

			
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("code", "0");
			jsonObject.put("msg", "操作失败");
		} finally {
			out = response.getWriter();
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		}
	}

	@ResponseBody
	@RequestMapping(value = "/saveOrUpdateAdminUser")
	public void saveOrUpdateAdminUser(HttpServletRequest request, HttpServletResponse response, AdminUser adminUser)
			throws Exception {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out;

		JSONObject jsonObject = new JSONObject();

		try {

			adminUserServcie.saveOrUpdateAdminUser(adminUser);

			jsonObject.put("code", "1");
			jsonObject.put("msg", "操作成功");
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("code", "0");
			jsonObject.put("msg", "操作失败");
		} finally {
			out = response.getWriter();
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		}
	}

	@ResponseBody
	@RequestMapping(value = "/delAdminUserById")
	public void delAdminUserById(HttpServletRequest request, HttpServletResponse response, Integer id)
			throws Exception {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out;

		JSONObject jsonObject = new JSONObject();

		try {

			adminUserServcie.delAdminUserById(id);

			jsonObject.put("code", "1");
			jsonObject.put("msg", "操作成功");
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("code", "0");
			jsonObject.put("msg", "操作失败");
		} finally {
			out = response.getWriter();
			out.print(jsonObject.toString());
			out.flush();
			out.close();
		}
	}

}
